package bb.lanxing.lib.devices.core.utils;

import bb.lanxing.lib.devices.api.DeviceStateListener;
import bb.lanxing.lib.devices.api.SmartDevice;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class DeviceStateNotifier {
    private Set<WeakReference<DeviceStateListener>> mListenerSet;

    public synchronized void notifyStateChanged(SmartDevice smartDevice, int i) {
        Set<WeakReference<DeviceStateListener>> set = this.mListenerSet;
        if (set != null) {
            for (WeakReference<DeviceStateListener> weakReference : set) {
                DeviceStateListener deviceStateListener = weakReference.get();
                if (deviceStateListener != null) {
                    deviceStateListener.onDeviceStateChanged(smartDevice, i);
                }
            }
        }
    }

    public synchronized void registerDeviceStateListener(DeviceStateListener deviceStateListener) {
        if (deviceStateListener == null) {
            return;
        }
        if (this.mListenerSet == null) {
            this.mListenerSet = new LinkedHashSet();
        }
        for (WeakReference<DeviceStateListener> weakReference : this.mListenerSet) {
            if (deviceStateListener.equals(weakReference.get())) {
                return;
            }
        }
        this.mListenerSet.add(new WeakReference<>(deviceStateListener));
    }

    public synchronized void unregisterDeviceStateListener(DeviceStateListener deviceStateListener) {
        if (deviceStateListener != null) {
            Set<WeakReference<DeviceStateListener>> set = this.mListenerSet;
            if (set != null && !set.isEmpty()) {
                Iterator<WeakReference<DeviceStateListener>> it = this.mListenerSet.iterator();
                while (it.hasNext()) {
                    WeakReference<DeviceStateListener> next = it.next();
                    if (deviceStateListener.equals(next.get())) {
                        next.clear();
                        it.remove();
                        return;
                    }
                }
            }
        }
    }

    public boolean isEmpty() {
        Set<WeakReference<DeviceStateListener>> set = this.mListenerSet;
        return set != null && set.isEmpty();
    }

    public synchronized void removeAllListeners() {
        Set<WeakReference<DeviceStateListener>> set = this.mListenerSet;
        if (set != null) {
            for (WeakReference<DeviceStateListener> weakReference : set) {
                weakReference.clear();
            }
            this.mListenerSet.clear();
        }
        this.mListenerSet = null;
    }
}
